package com.xixing.weixin.cmd;

import com.xixing.weixin.exception.AccountException;
import com.xixing.weixin.exception.ArgumentException;
import com.xixing.weixin.exception.WeixinExecuteException;
import com.xixing.weixin.domain.Account;
import com.xixing.weixin.domain.Weixin;
import com.xixing.weixin.response.ArticleItem;
import com.xixing.weixin.response.ArticleResponse;
import com.xixing.weixin.response.Response;
import com.xixing.weixin.response.TextResponse;
import com.xixing.weixin.utils.GzhuLibraryUtils;
import com.xixing.weixin.utils.GzhuSchoolUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.dao.EmptyResultDataAccessException;

import java.util.List;
import java.util.ResourceBundle;


public class BookExecutor extends AbstractExecutor {

    public static class Arg {
        public Arg() {
        }

        public boolean isDefault;
        public String bookName;

        @Override
        public String toString() {
            return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
        }
    }


    @Override
    public Response execute(Weixin weixin, Object args) throws WeixinExecuteException {
        if (!(args instanceof Arg)) throw new ArgumentException();
        Arg arg = (Arg) args;
        if (arg.bookName == null) throw new ArgumentException();
        if (arg.isDefault == true) throw new ArgumentException();

        try {
            String html = GzhuLibraryUtils.findBook(arg.bookName);
            //FIXME 图书为空的情况
            List<ArticleItem> articleItems = GzhuLibraryUtils.parseBook(html);
            if(articleItems.size() == 0){
                return TextResponse.create(weixin, ResourceBundle.getBundle("template").getString("BOOK_NOT_FOUND"));
            }
            return ArticleResponse.create(weixin,articleItems);
        } catch (Exception e) {
            throw new ArgumentException();
        }

    }

    @Override
    public Object parseArgs(Weixin weixin, Object args) throws WeixinExecuteException {

        assertWeixinMsgType(weixin, Weixin.TEXT);
        assertWeixinContentLength(weixin, 1, 2);

        Arg arg = new Arg();
        arg.isDefault = true;

        String[] contentArgs = AbstractExecutor.splitCommand(weixin.getContent());
        String temp = AbstractExecutor.normalCommand(contentArgs[0]);
        if (isCommand(temp)) {
            if (contentArgs.length > 1) {
                arg.bookName = contentArgs[1];
                arg.isDefault = false;
            }
        } else {
            arg.bookName = contentArgs[0];
            arg.isDefault = false;
        }
        return arg;
    }

}
